import {
	showMessage
} from "./helper";

import store from "../store";

//const base = "http://49.235.168.145:3333"
const base = "https://rent-api.anta123.com"
const UserKey = 'KEY_USER_INFO';
const TokenKey = "KEY_TOKEN"
function request(url, method, data, header) {

	var user = uni.getStorageSync(UserKey)

	return new Promise((resolve, reject) => {
		uni.request({
			url: base + url, //仅为示例，并非真实接口地址。
			method: method,
			data: data,
			header: {
				...(user ? {
					'Cusauthorization': user.token
				} : {}),
				"Content-Type": "application/json",
				...header
			},
			fail: (err) => {
				reject(err)
			},

			success: (res) => {
				var code = res.data.statusCode;
				if (code == 0) {
					resolve(res.data)
				} else if (code == '6001') {
					showMessage('Login is invalid, please login again')
					store.dispatch('removeUser')
				} else if (code == '1402') {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				} else {
					resolve(res.data);
					showMessage(res.data.message || 'System Error')
					reject()
				}
			}
		});
	})
}

export function query(url, data, header) {
	return request(url, 'GET', data, header)
}

export function post(url, data, header) {
	return request(url, 'POST', data, header)
}

export function remove(url, data, header) {
	return request(url, 'DELETE', data, header)
}